package com.yunbiao.ybbusstopplate.utils.core.power;

import android.text.TextUtils;
import android.util.Log;

import com.example.library_hy_advert.system.Path;
import com.yunbiao.ybboardapi.action.SLX560Action;
import com.yunbiao.ybbusstopplate.base.APP;
import com.yunbiao.ybbusstopplate.base.HeartBeatClient;
import com.yunbiao.ybbusstopplate.utils.CommonUtils;
import com.yunbiao.ybbusstopplate.utils.cache.ACache;
import com.yunbiao.ybbusstopplate.utils.cache.LayoutCache;
import com.yunbiao.ybbusstopplate.utils.core.TYTool;
import com.yunbiao.ybbusstopplate.utils.net.ResourceUpdate;
import com.yunbiao.ybbusstopplate.utils.xutil.MyXutils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PowerOffTool {

    private static PowerOffTool powerOffTool = null;

    private PowerOffTool() {
    }

    public static PowerOffTool getPowerOffTool() {
        if (powerOffTool == null) {
            synchronized (PowerOffTool.class) {
                if (powerOffTool == null) {
                    powerOffTool = new PowerOffTool();
                }
            }
        }
        return powerOffTool;
    }

    public final static String POWER_ON = "poerOn";
    public final static String POWER_OFF = "poerOff";

    private void putPowerParam(String key, String value) {
        ACache.get(new File(Path.getOnlinePropertyCache())).put(key, value);
    }

    /**
     * @return 1, 2, 3, 4, 5, 6, 7;08:00
     */
    public String getPowerParam(String key) {
        return ACache.get(new File(Path.getOnlinePropertyCache())).getAsString(key);
    }

    private void setPowerRestartTime() {
        Integer type = CommonUtils.getBroadType();
        Log.d("poweroff--板子", "setPowerRestartTime: " + type);
        switch (type.intValue()) {
            case 0:
//                setChuangwei();
                setPowerRunTime();
                break;
            case 1:
                setZHPoweroff();
                break;
            case 2:
                setHongShiDa();
                break;
            case 3:
            case 31:
            case 4:
            case 6:
                setYiSheng(type);
                break;
            case 5:
                setJYD();
                break;
            case 7:
                JDFPowerControl.getInstance().powerOnOffTool();
                break;
            case 8:
                break;
            case 9:
                PowerControllerTool.getPowerContrArray(SLX560Action.ACTION_SETPOWERONOFF);
                break;
        }
    }

    // TODO: 2020/12/4 test
    //10分钟后关机，五分钟之后开机
    private void testPowerOffTime(){
        Calendar calendar_on = Calendar.getInstance();
        calendar_on.add(Calendar.MINUTE,15);
        String powerOn ="1,2,3,4,5,6,7,;"+calendar_on.get(Calendar.HOUR_OF_DAY)+":"+calendar_on.get(Calendar.MINUTE);

        Calendar calendar_off = Calendar.getInstance();
        calendar_off.add(Calendar.MINUTE,10);
        String powerOff ="1,2,3,4,5,6,7,;"+calendar_off.get(Calendar.HOUR_OF_DAY)+":"+calendar_off.get(Calendar.MINUTE);
        // 1,2,3,4,5,6,7;08:00
        putPowerParam(POWER_ON, powerOn);
        putPowerParam(POWER_OFF, powerOff);

        setPowerRestartTime();
    }

    private void testPowerOffTime2(){
        String time="{\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "            \"eTime\": \"15:40\",\n" +
                "            \"sTime\": \"15:50\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"eTime\": \"16:00\",\n" +
                "            \"sTime\": \"16:10\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"type\": 1,\n" +
                "    \"week\": \"1,2,3,4,5,6,7\"\n" +
                "}";
        time=time.replace("\n","").trim();
        String[] powers = PowerSelectTool.getInstance().selectPowerSettimes(time);
        if (powers!=null){
            for (int i = 0; i < powers.length; i++) {
                System.out.println("--->"+i+"=="+powers[i]);
            }
            // 1,2,3,4,5,6,7;08:00
            putPowerParam(POWER_ON, powers[0]);
            putPowerParam(POWER_OFF, powers[1]);

            setPowerRestartTime();
        }
    }
    /**
     * 获取开关机时间
     *
     * @param uid 设备id
     */
    public void getPowerOffTime(String uid) {
//        testPowerOffTime2();

        getPowerOffTimeNew(uid);//多时段开关机
//        getPowerOffTimeOld(uid);
    }

    private void getPowerOffTimeNew(final String uid){
        Map<String, String> params=new HashMap<>();
        params.put("deviceNo",uid);
        Log.d("powerofftool", "getPowerOffTimeNew-----------URL------- "+ResourceUpdate.MULTI_POWER_OFF_URL);
        MyXutils.getInstance().post(ResourceUpdate.MULTI_POWER_OFF_URL, params, new MyXutils.XCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.d("powerofftool", "getPowerOffTimeNew------------------onSuccess: "+result);
                try {
                    JSONObject resultObj=new JSONObject(result);
                    int status = resultObj.getInt("status");
                    if (status==1){
                        putMultiPower(uid,result);
                    }else {
                        putMultiPower(uid,"");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    putMultiPower(uid,"-1");
                }
            }

            @Override
            public void onError(Throwable ex) {
                Log.d("powerofftool", "getPowerOffTimeNew------------------onError: "+ex.getMessage());
                putMultiPower(uid,"-1");
            }

            @Override
            public void onFinish() {

            }
        });
    }

    private void putMultiPower(final String uid, final String powerTime){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!"-1".equals(powerTime)){
                    LayoutCache.setMultiPowerTime(powerTime);
                }
                String multiPowerTime = LayoutCache.getMultiPowerTime();
                if (TextUtils.isEmpty(multiPowerTime)){
                    //查看原始开关机，防止旧设备开关机失效
                    getPowerOffTimeOld(uid);
                }else {
                    //多时段开关机
                    String[] powers = PowerSelectTool.getInstance().selectPowerSettimes(multiPowerTime);
                    // 1,2,3,4,5,6,7;08:00
                    putPowerParam(POWER_ON, powers[0]);
                    putPowerParam(POWER_OFF, powers[1]);

                    setPowerRestartTime();
                }
            }
        }).start();
    }

    private void getPowerOffTimeOld(String uid){
        HashMap<String, String> paramMap = new HashMap();
        paramMap.put("uid", uid);
        Log.d("powerofftool", "getPowerOffTimeOld-----------URL------- "+ResourceUpdate.POWER_OFF_URL);
        MyXutils.getInstance().post(ResourceUpdate.POWER_OFF_URL, paramMap, new MyXutils.XCallBack() {
            @Override
            public void onSuccess(String result) {

                Log.d("powerofftool", "getPowerOffTimeOld------------------onSuccess: "+result);
                if (result.startsWith("\"")) {
                    result = result.substring(1, result.length() - 1);
                }
//                putParam(result);

                final String power=result;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        putParam(power);
                    }
                }).start();
            }

            @Override
            public void onError(Throwable ex) {
                Log.d("powerofftool", "getPowerOffTimeOld------------------onError: "+ex.getMessage());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        setPowerRestartTime();
                    }
                }).start();
            }

            @Override
            public void onFinish() {

            }
        });
    }

    private void putParam(String powerOffJson) {
        powerOffJson = powerOffJson.replaceAll("\\\\", "");
        if (powerOffJson.startsWith("\"")) {
            powerOffJson = powerOffJson.substring(1, powerOffJson.length() - 1);
        }
        JSONTokener jsonParser = new JSONTokener(powerOffJson);
        try {
            // 开机字符串
            String powerOn = "";
            // 关机字符串
            String powerOff = "";

            JSONArray person = (JSONArray) jsonParser.nextValue();
            for (int i = 0; i < person.length(); i++) {
                JSONObject jsonObject = (JSONObject) person.get(i);
                Integer status = jsonObject.getInt("status");
                Integer runType = jsonObject.getInt("runType");
                String runDate = jsonObject.getString("runDate");
                if (runDate.indexOf(":") != -1) {
                    runDate = runDate.substring(runDate.indexOf(":") + 1, runDate.length());//1,2,3,4,5,6,7,
                }

                String runTime = jsonObject.getString("runTime");
                if (runType == 0 && status == 0) {
                    powerOn = runDate + ";" + runTime;
                } else if (runType == 1 && status == 0) {
                    powerOff = runDate + ";" + runTime;
                }
            }

            // 1,2,3,4,5,6,7;08:00
            putPowerParam(POWER_ON, powerOn);
            putPowerParam(POWER_OFF, powerOff);

            setPowerRestartTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*如果没有正常关机，中途启动了就再次关机*/
    private void executefailedPowerDown() {
        // 获取当天星期几
        Date currentDate = new Date();
        Integer weekDay = getWeekDay(currentDate);
        // 获取时间
        String poweroff = getPowerParam(POWER_OFF);
        if (!TextUtils.isEmpty(poweroff)) {
            // 判断是否存在运行策略
            String[] powerOnArray = poweroff.split(";");
            String runDate = powerOnArray[0];
            String runTime = powerOnArray[1];
            String[] timeDateArray = runTime.split(":");

            String currentTime = CommonUtils.getStringDate();
            String[] timePice = currentTime.split(":");
            int currentHour = Integer.valueOf(timePice[0]);
            int currentMinute = Integer.valueOf(timePice[1]);
            int closeHour = Integer.valueOf(timeDateArray[0]);
            int closeMinute = Integer.valueOf(timeDateArray[1]);

            if (runDate.indexOf(weekDay.toString()) != -1) {// 如果当天是运行策略中包含的周期
                int intervalTime = 6;
                if (currentHour > closeHour) {
                    intervalTime = 60 - closeMinute + currentMinute;
                } else if (currentHour == closeHour) {
                    intervalTime = Math.abs(currentMinute - closeMinute);
                }
                setPowerFailedDown(intervalTime);
            }
        }
    }

    /*//开关机失败。间隔时间小于5秒，重设开关机时间*/
    private void setPowerFailedDown(int intervalTime) {
        if (intervalTime < 5) {
            Long[] powerOn = getPowerTime(POWER_ON);
            if (powerOn != null) {
                Long onh = powerOn[0] * 24 + powerOn[1];
                Long onm = powerOn[2];
                if ((onh * 60 + onm) > 2) {
                    OnOffTool.setEnabled(onh.byteValue(), onm.byteValue(), (byte) 0, (byte) 2);
                }
            }
        }
    }

    /**
     * 单机版开关机设置
     *
     * @param powerOn
     * @param powerOff
     */
    public void setLocalRuntime(String powerOn, String powerOff) {
        if (powerOn != null && !powerOn.isEmpty() && powerOff != null && !powerOff.isEmpty()) {
            putPowerParam(POWER_ON, "1,2,3,4,5,6,7;" + powerOn);
            putPowerParam(POWER_OFF, "1,2,3,4,5,6,7;" + powerOff);
        } else {
            putPowerParam(POWER_ON, "");
            putPowerParam(POWER_OFF, "");
        }
        // 执行设置运行
        setPowerRestartTime();
    }

    /**
     * 机器重启
     */
    public void restart() {
//        OnOffTool.setEnabled((byte) 0, (byte) 1, (byte) 0, (byte) 1);
        Integer type = CommonUtils.getBroadType();
        switch (type) {
            case 1:
                ZHBroadControl.getZhBroadControl().rebootMachine();
                break;
            case 4:
                TYTool.sendBroadcast(XBHActions.ACTION_REBOOT);
                break;
            case 5:
                TYTool.sendBroadcast(JYDActions.ACTION_REBOOT);
                break;
            case 6:
                TYTool.sendBroadcast(QJAction.ACTION_REBOOT);
                break;
            case 9:
                SLX560Action.getInstance().powerReboot(APP.Companion.getAppContext());
                break;
            default:
                execSuCmd("reboot");
                break;
        }
    }

    public void execSuCmd(String cmd) {
        Process process = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            int aa = process.waitFor();
            is = new DataInputStream(process.getInputStream());
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            String out = new String(buffer);
            Log.i("tag", out + aa);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                process.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置机器的开关机时间
     */
    public void setPowerRunTime() {
        Long[] powerOn = getPowerTime(POWER_ON);
        Long[] powerOff = getPowerTime(POWER_OFF);
        // 如果开关机时间没有设置，就进行网络获取
        if (powerOn != null && powerOff != null) {
            Long offh = powerOff[0] * 24 + powerOff[1];
            Long offm = powerOff[2];
            // 0 23 26
            // onh:0 onm:1
            // 0 23 25
            // offh:23 offm:25
            Long onh = powerOn[0] * 24 + powerOn[1];
            Long onm = powerOn[2];
            if ((onh * 60 + onm) > (offh * 60 + offm)) {
                long offset = (onh * 60 + onm) - (offh * 60 + offm);
                onm = offset % 60;
                onh = offset / 60;
            }
            OnOffTool.setEnabled(onh.byteValue(), onm.byteValue(), offh.byteValue(), offm.byteValue());
            Log.e("time::::", "onh:" + onh + "======onm:" + onm + "========offh:" + offh + "======offm:" + offm);
            executefailedPowerDown();
        } else {
            Log.e("time", "没有找到开关机时间");
            OnOffTool.setDisabled();
        }
    }

    /**
     * 机器开机时候，判断是否需要到网络查询
     */
    public void machineStart() {
//        Long[] powerOn = getPowerTime(POWER_ON);
//        Long[] powerOff = getPowerTime(POWER_OFF);
//        // 如果开关机时间没有设置，就进行网络获取
//        if (powerOn != null && powerOff != null) {
//            setPowerRestartTime();
//        } else {
//            //开关机时间为空，则去网络下载
//            getPowerOffTime(HeartBeatClient.getDeviceNo());
//        }

        getPowerOffTime(HeartBeatClient.getDeviceNo());
    }

    /**
     * 获取下一个开关机时间
     *
     * @param powerType
     * @return
     */
    public Long[] getPowerTime(String powerType) {
        Long[] runTimeLong = null;
        // 获取当天星期几
        Date currentDate = new Date();
        Integer weekDay = getWeekDay(currentDate);
        // 获取时间
        String powerOn = getPowerParam(powerType);
        if (!TextUtils.isEmpty(powerOn)) {
            // 判断是否存在运行策略
            String[] powerOnArray = powerOn.split(";");
            String runDate = powerOnArray[0];
            String runTime = powerOnArray[1];
            String[] timeDateArray = runTime.split(":");
            Date onDate = new Date();
            onDate.setHours(Integer.parseInt(timeDateArray[0]));
            onDate.setMinutes(Integer.parseInt(timeDateArray[1]));
            boolean isEq = false;
            if (onDate.getHours() == currentDate.getHours() && onDate.getMinutes() == currentDate.getMinutes()) {
                currentDate.setMinutes(currentDate.getMinutes() + 3);
                isEq = true;
            }
            if (runDate.indexOf(weekDay.toString()) != -1) {// 如果当天是运行策略中包含的周期
                if (onDate.getTime() > currentDate.getTime()) {
                    // 如果开机时间大于当前时间，就需要设置
                    Long betwLong = onDate.getTime() - currentDate.getTime();
                    runTimeLong = formatDuring(betwLong);
                } else {
                    // 推迟到运行周期中的下一天的这个时间
                    Integer betweenDay = getBetweenDay(runDate, weekDay);
                    if (powerType.equals(POWER_ON) && isEq) {
                        onDate.setMinutes(onDate.getMinutes() + 3);
                    }
                    onDate.setDate(onDate.getDate() + betweenDay);
                    runTimeLong = formatDuring(onDate.getTime() - currentDate.getTime());
                }
            } else {
                // 如果运行策略中没有这一天
                Integer nextDay = getNextDay(runDate);
                onDate.setDate(onDate.getDate() + nextDay);
                if (powerType.equals(POWER_ON) && isEq) {
                    onDate.setMinutes(onDate.getMinutes() + 3);
                }
                runTimeLong = formatDuring(onDate.getTime() - currentDate.getTime());
            }
        }
        return runTimeLong;
    }

    public Integer getNextDay(String runDate) {
        Integer between = 1;
        if (TextUtils.isEmpty(runDate)){
            return between;
        }
        boolean hasData=false;
        String[] split = runDate.split(",");
        for (String s:split) {
            if (!TextUtils.isEmpty(s)){
                hasData=true;
                break;
            }
        }
        if (!hasData){
            return between;
        }
        Calendar calendar = Calendar.getInstance();
        while (true){
            calendar.add(Calendar.DAY_OF_MONTH,1);
            String week = getWeekDay(calendar.getTime()) + "";
            if (runDate.indexOf(week)!=-1){
                break;
            }
            between=between+1;
        }
        return between;
    }

    public Integer getBetweenDay(String runDate, Integer currentWeekDay) {
        Integer between = 0;
        String[] runDateArray = runDate.split(",");
        for (int i = 0; i < runDateArray.length; i++) {
            Integer runDateA = Integer.parseInt(runDateArray[i]);
            if (runDateA == currentWeekDay) {
                if (i == runDateArray.length - 1) {
                    between = Integer.parseInt(runDateArray[0]) + (7 - currentWeekDay);
                } else {
                    runDateA = Integer.parseInt(runDateArray[i + 1]);
                    between = runDateA - currentWeekDay;
                }
                break;
            }
        }
        return between;
    }

    /**
     * 获取时间间隔
     *
     * @param mss
     * @return
     */
    public Long[] formatDuring(Long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return new Long[]{days, hours, minutes, seconds};
    }

    public Integer getWeekDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        int week = calendar.get(Calendar.DAY_OF_WEEK);
        if (week==1){
            week=7;
        }else {
            week=week-1;
        }
        return week;
    }

    /**
     * 机器重启
     */
    public void powerReload() {
        String cmd = "su -c reboot";
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
        }
    }

    /**
     * 机器关机
     */
    public void powerShutdown() {
        Integer type = CommonUtils.getBroadType();
        switch (type) {
            case 4:
                TYTool.sendBroadcast(XBHActions.ACTION_SHUTDOWN);
                break;
            case 5:
                TYTool.sendBroadcast(JYDActions.ACTION_SHUTDOWN);
                break;
            case 6:
                TYTool.sendBroadcast(QJAction.ACTION_SHUTDOWN);
                break;
            case 9:
                SLX560Action.getInstance().powerShutdown(APP.Companion.getAppContext());
                break;
            default:
                Process process = null;
                try {
                    process = Runtime.getRuntime().exec("su");
                    DataOutputStream out = new DataOutputStream(process.getOutputStream());
                    out.writeBytes("reboot -p\n");
                    out.writeBytes("exit\n");
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * 中恒板子开关机接口
     * String msg="[{checkSwitch:true,type:0,settings:[
     * {switch:true,wakeupTime:\"10:05\",sleepTime:\"10:45\",week:[\"tuesday\",\"thursday\",\"saturday\"]},
     * {switch:true,wakeupTime:\"11:05\",sleepTime:\"11:45\",week:[\"tuesday\",\"thursday\",\"saturday\"]}
     * ]}]";
     */
    public void setZHPoweroff() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("checkSwitch", "true");
            jsonObject.put("type", 0);
            String powerOn = getPowerParam(POWER_ON);
            String powerOff = getPowerParam(POWER_OFF);
            if (!TextUtils.isEmpty(powerOn) && !TextUtils.isEmpty(powerOff)) {
                String[] powerOnStirng = powerOn.split(";");
                String[] powerOffStirng = powerOff.split(";");
                if (powerOnStirng.length == 2) {
                    String powerOnTime = powerOnStirng[1];
                    String powerOffTime = powerOffStirng[1];
                    JSONArray jsonArray = new JSONArray();
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("switch", "true");
                    jsonObject1.put("wakeupTime", powerOnTime);
                    jsonObject1.put("sleepTime", powerOffTime);
                    JSONArray weekArray = getjsonArray(powerOnStirng[0]);
                    jsonObject1.put("week", weekArray);
                    jsonArray.put(jsonObject1);
                    jsonObject.put("settings", jsonArray);
                }
            } else {
                JSONArray jsonArray = new JSONArray();
                jsonObject.put("settings", jsonArray);
            }

            ZHBroadControl.getZhBroadControl().setPowerOnOff(String.valueOf(jsonObject));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*中恒板子接口用*/
    private JSONArray getjsonArray(String powerOnStirng) {
        JSONArray jsonArray = new JSONArray();
        String[] weekNumbers = powerOnStirng.split(",");
        for (int i = 0; i < weekNumbers.length; i++) {
            switch (i) {
                case 1:
                    jsonArray.put("monday");
                    break;
                case 2:
                    jsonArray.put("tuesday");
                    break;
                case 3:
                    jsonArray.put("wednesday");
                    break;
                case 4:
                    jsonArray.put("thursday");
                    break;
                case 5:
                    jsonArray.put("friday");
                    break;
                case 6:
                    jsonArray.put("saturday");
                    break;
                case 7:
                    jsonArray.put("sunday");
                    break;
            }
        }
        return jsonArray;
    }

    /*设置深圳鸿世达科技板子 开关机*/
    private void setHongShiDa() {
        new HongShiDaBroadControl();
    }

    /*设置亿晟板子 开关机*/
    private void setYiSheng(int type) {
        new YiShengBroadControl();
    }

    /*设置建益达板子 开关机*/
    private void setJYD() {
        new JYDBroadControl();
    }



}
